/*****************************************************************************************
 **  Author:jxx 2022
 **  QQ:283591387
 **完整文档见：http://v2.volcore.xyz/document/api 【代码生成页面ViewGrid】
 **常用示例见：http://v2.volcore.xyz/document/vueDev
 **后台操作见：http://v2.volcore.xyz/document/netCoreDev
 *****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
// import modelHeader from "../../inventoryinfo/goods_inventory_warehouse_xm/goodsInventoryWarehouse_xm.vue"
import modelHeader from "../../inventoryinfo/goodsin_class/goodsInCom.vue"
import gridHeader from "@/components/print/selectTemplet.vue"
import {
  mapMutations
} from "vuex";
let extension = {
  components: {
    //查询界面扩展组件
    gridHeader,
    gridBody: '',
    gridFooter: '',
    //新建、编辑弹出框扩展组件
    modelHeader: modelHeader,
    modelBody: '',
    modelFooter: ''
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: {
    view: [],
    box: [],
    detail: []
  }, //扩展的按钮

  methods: {
    ...mapMutations(
      ("salesContractMX", ["storeRemoveForm", "storeChangeForm"])
    ),
    //下面这些方法可以保留也可以删除
    async onInit() {
      // this.queryFields = [ "Client","Voucher_sub"]//,"Delivery_time"
      this.queryFields = ["Client", "Delivery_time"] //,"Delivery_time"
      this.boxOptions.labelWidth = 130;
      let startTime = await this.base.getOneWeekAgoDate()
      let endTime = await this.base.getDate(false) + " 23:59:59"
      this.searchFormFields.Delivery_time = [startTime, endTime]
      this.textInline = false
      this.detailOptions.textInline = false
      this.single = true
      this.editFormOptions.forEach(x => {
        x.forEach(item => {
          if (item.field == 'Attachment' || item.field == 'Image') {
            item.multiple = true;
            item.maxFile = 10;
          }
        })
      })
      if (this.$route.path == "/q_sales_contract" && JSON.stringify(this.$route.query) != '{}') {
        console.log("触发查询")
        await this.base.setSearchParamFn(this)
        // this.searchFormFields.Voucher_sub = null
        // this.searchFormFields.Client = null
        // this.searchFormFields.Signed_num = null
        // this.searchFormFields.Check_out_flag = null
        // this.searchFormFields.Delivery_mode = null
        // this.searchFormFields.AuditStatus = null
        // this.searchFormFields.Contract_intro = null
        // this.searchFormFields.Delivery_time = [null, null]
        // const selectList = ['Voucher_sub','Signed_num','Contract_intro',]
        // this.searchFormOptions.forEach(item => {
        //   item.forEach(x => {
        //     if (!selectList.includes(x.field)) {
        //       x.onChange = (v) => {
        //         this.$route.query = {}
        //       }
        //     }
        //   })
        // })
        setTimeout(() => {
          this.refresh()
        })
      }
    },
    async onInited() {
      if (this.$route.path != "/q_sales_contract") {
        this.setFiexdSearchForm(true);
        this.height = 550 - 150;
        this.buttons.forEach(item => {
          if (item.value != "Search") {
            item.hidden = true
          }
        })
        this.detailOptions.buttons = []
        this.boxButtons[0].hidden = true
        this.searchFormFields.AuditStatus = "1"
        // this.searchFormFields.Delivery_time = [
        //   this.base.getDate(),
        //   "",
        // ];
      }
      // await this.setFiexdSearchForm(true);
      // await this.buttons.forEach(item => {
      //   if (item.name == "高级查询") {
      //     item.hidden = true
      //   }
      // })
      let indexNum = this.detailOptions.buttons.findIndex(item => item.name == "添加行")
      if (indexNum != "-1") {
        this.detailOptions.buttons.splice(indexNum, 1)
      }
      await this.detailOptions.buttons.unshift({
        name: "选择商品",
        icon: 'el-icon-plus',
        type: 'primary',
        plain: true,
        onClick: function () {
          if (this.rowschild) {
            this.rowschild.click()
          }
          // this.$refs.modelHeader.open()
          // let form = {
          //   AuditStatus: 1
          // }
          // this.storeChangeForm(form);
          this.$store.commit("setTabelText", true)
          // if (!this.editFormFields.WHSE_Id) {
          //   this.base.ElMessageFn("请先选择出库机构")
          //   return false;
          // } else if (!this.editFormFields.Tax_rate) {
          //   this.base.ElMessageFn("请先选择税率")
          //   return false;
          // }
          // this.$refs.modelHeader.open(this.editFormFields.WHSE_Id)
          this.$refs.modelHeader.detailOpen()
        }
      })


      this.detailOptions.beginEdit = (row, column, index) => {
        if (this.$route.path != "/q_sales_contract" || this.rowAuditStatus != 0) { // || !this.CreateUserBoole
          return false
        } else {

          this.detailOptions.columns.forEach(item => {
            if (item.field == "Install_status") {
              item.bind.data.forEach(d => {
                if (d.key != 0 && d.key != 3) {
                  d.hidden = true
                } else {
                  d.hidden = false
                }
              })
            }
            // if (item.field == "WHSE_name") {

            //   let selectUrl = `api/q_warehouse_locationList/getgoodslocation?bm=${row.Goods_sub}`
            //   item.bind.data.forEach(d => {
            //     d.hidden = true
            //   })
            //   this.http.post(selectUrl, {}, "").then(reslut => {
            //     item.bind.data.forEach(d => {
            //       d.hidden = true
            //     })
            //     item.bind.data.forEach(d => {
            //       reslut.rows.forEach(j => {
            //         if (d.key == j.WHSE_no) {
            //           d.hidden = false
            //         }
            //       })
            //     })
            //   })

            //   // item.onChange = (column, row, tableData) => {
            //   //   if (column.Goods_num) {
            //   //     this.getInventoryNum(column, column.Goods_num)
            //   //   }
            //   // }
            // }
          })

          let rows = document.querySelectorAll(".grid-detail .el-table__body .el-table__row")
          this.rowschild = rows[0].childNodes[2]
          setTimeout(() => {
            //数量
            let testInputDom = rows[index].querySelectorAll("td")[5].querySelector("input")
            testInputDom.addEventListener("keyup", (e) => {

              // if (!+row.Goods_price && +row.Goods_price != 0) {
              if (!+row.Goods_price && +row.Goods_price != 0) {
                row.Total_price = ""
                row.Tax_exclusive_goods_price = ""
                row.Tax_exclusive_total_price = ""
                return this.base.ElMessageFn("请正确输入单价")
              }
              if ((+row.Goods_price < 0 && row.Goods_price) && (row.Goods_price !== 0 || row.Goods_price !== "0")) {
                row.Total_price = ""
                row.Tax_exclusive_goods_price = ""
                row.Tax_exclusive_total_price = ""
                return this.base.ElMessageFn("单价请大于零")
              }
              if (+e.target.value && +e.target.value > 0 || e.target.value == "" && row.Goods_price) {
                row.Total_price = row.Goods_price * e.target.value
                if (this.editFormFields.Tax_rate) {
                  let num = row.Goods_price / (1 + +this.editFormFields.Tax_rate)
                  row.Tax_exclusive_goods_price = this.base.roundToFourDecimals(num)
                  // let num2 = row.Goods_price  / (1 + +this.editFormFields.Tax_rate)* e.target.value
                  let wsjg = row.Goods_price / (1 + +this.editFormFields.Tax_rate)
                  wsjg = this.base.roundToFourDecimals(wsjg)
                  let num2 = wsjg * e.target.value
                  row.Tax_exclusive_total_price = this.base.roundToFourDecimals(num2)
                }
              } else {
                row.Total_price = ""
                row.Tax_exclusive_total_price = ""
                this.base.ElMessageFn("请正确输入数量")
              }
            })
            //单价
            let testInputDom2 = rows[index].querySelectorAll("td")[6].querySelector("input")
            testInputDom2.addEventListener("keyup", (e) => {
              if (!+row.Goods_num && +row.Goods_num != 0) {
                row.Total_price = ""
                row.Tax_exclusive_total_price = ""
                return this.base.ElMessageFn("请正确输入数量")
              }
              if (+row.Goods_num <= 0 && row.Goods_num) {
                row.Total_price = ""
                row.Tax_exclusive_total_price = ""
                return this.base.ElMessageFn("数量请大于零")
              }
              if (e.target.value ? ("" + e.target.value).trim() === "0" : e.target.value === 0) {
                row.Tax_exclusive_goods_price = 0
                row.Tax_exclusive_total_price = 0
                row.Total_price = 0
                return
              }
              if (+e.target.value && +e.target.value > 0 || e.target.value == "" && row.Goods_num) {
                row.Total_price = row.Goods_num * e.target.value
                if (this.editFormFields.Tax_rate) {
                  let num = e.target.value / (1 + +this.editFormFields.Tax_rate)
                  row.Tax_exclusive_goods_price = this.base.roundToFourDecimals(num)
                  // let num2 = row.Goods_num  / (1 + +this.editFormFields.Tax_rate)* e.target.value
                  let wsjg = row.Goods_num / (1 + +this.editFormFields.Tax_rate)
                  wsjg = this.base.roundToFourDecimals(wsjg)
                  let num2 = wsjg * e.target.value
                  row.Tax_exclusive_total_price = this.base.roundToFourDecimals(num2)
                }
                return
              } else {
                row.Total_price = ""
                row.Tax_exclusive_goods_price = ""
                row.Tax_exclusive_total_price = ""
                this.base.ElMessageFn("请正确输入单价")
              }

            })
            // let GoodsPriceInputDom = rows[index].querySelectorAll("td")[5].querySelector("input")
            // GoodsPriceInputDom.addEventListener("keyup", (e) => {
            //   console.log(e.target.value);
            //   if (+e.target.value && +e.target.value > 0 || e.target.value == "") {
            //     if (row.Goods_num) {
            //       row.Total_price = (row.Goods_num * e.target.value).toFixed(2)
            //     }
            //   } else {
            //     if (this.messageError) {
            //       this.messageError.close();
            //     }
            //     this.messageError = this.$message.error("请正确输入价格")
            //   }
            // })
          }, 0)
          return true
        }
      }

    },
    WHSE_IdDisableFn() {
      this.editFormOptions.forEach(item => {
        item.forEach(x => {
          if (x.field == 'WHSE_no') {
            x.disabled = true
          }
        })
      })
    },
    async searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      if (this.$route.path != "/q_sales_contract") {
        param.wheres = param.wheres.filter(item => item.name != "Sales_contract")
        this.$route.query = {}
      }
      if (this.$route.path == "/q_sales_contract" && JSON.stringify(this.$route.query) != '{}') {
        await this.base.setSearchBefore(this, "Sales_contract", param)
        // const sectionState = ["[null,null]",JSON.stringify(["",null]),JSON.stringify([null,""]),JSON.stringify(["",""])]
        // const dateState=sectionState.includes(JSON.stringify(this.searchFormFields.Delivery_time))
        // if (this.searchFormFields.Voucher_sub||this.searchFormFields.Signed_num||this.searchFormFields.Contract_intro ||!dateState) {
        //    param.wheres=param.wheres.filter(item=>item.name!="Sales_contract")
        //   this.$route.query = {}
        // }
      }
      return true;
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      // this.base.proNumRegBefore(result, "Signed_price", "Signed_num")

      return true;
    },
    searchDetailAfter(data, result) {
      //处理子表数据展示前和主表税率一致
      let tax_rate = this.editFormFields.Tax_rate
      let rows = result.rows
      if (rows && tax_rate) {
        rows.forEach(item => {
          if (item.Goods_price) {
            let goods_price = item.Goods_price / (1 + +tax_rate)
            item.Tax_exclusive_goods_price = this.base.roundToFourDecimals(goods_price)
            if (item.Goods_num) {
              // let goods_priacSum = item.Goods_price / (1 + +tax_rate) * item.Goods_num
              let wsjg = item.Goods_price / (1 + +tax_rate)
              wsjg = this.base.roundToFourDecimals(wsjg)
              let goods_priacSum = wsjg * item.Goods_num
              item.Tax_exclusive_total_price = this.base.roundToFourDecimals(goods_priacSum)
            }
          }
        })
      }
      return true;
    },
    delBefore(ids, rows) { //查询界面的表删除前 ids为删除的id数组,rows删除的行
      let auditStatus = rows.some(x => {
        return x.AuditStatus == 1
      });
      if (auditStatus) {
        this.base.ElMessageFn('不支持删除审核通过数据')
        return false;
      }
      return true;
    },
    addBeforeAsync(formData) {
      return this.testAdd(formData)
    },
    async updateBeforeAsync(formData) {
      return this.testAdd(formData)
    },
    rowClick({
      row,
      column,
      event
    }) {
      //查询界面点击行事件
      this.$refs.table.$refs.table.toggleRowSelection(row);
    },
    detailRowClick({
      row,
      column,
      event
    }) {
      this.$refs.detail.$refs.table.toggleRowSelection(row);
      if (this.$route.path != "/q_sales_contract" || this.rowAuditStatus != 0) {
        return
      }; //|| !this.CreateUserBoole
      if (column.property == "Goods_num" || column.property == "Goods_price" || column.property == "Remark") {
        let dom = event.target
        if (dom.nodeName != "SPAN") {
          setTimeout(() => {
            let inpDom = dom.querySelector("input")
            inpDom.focus()
          }, 0)
        }

      }
    },
    delDetailRow(rows) { //弹出框删除明细表的行数据(只是对table操作，并没有操作后台)
      try {
        if (rows.length == this.$refs.detail.rowData.length) {
          this.$store.commit("setWHSE_time", true)
          this.$store.commit("setWHSE_disabled", true)
          this.WHSE_Interval = setInterval(() => {
            console.log("WHSE_Interval", this.WHSE_Interval)
            this.editFormOptions.forEach(item => {
              item.forEach(x => {
                if (x.field == 'WHSE_no') {
                  if (this.$store.state.WHSE_disabled) {
                    x.disabled = true
                  } else {
                    x.disabled = false
                  }
                }
              })
            })
            if (!this.$store.state.WHSE_time) {
              clearInterval(this.WHSE_Interval)
              console.log("WHSE_Interval清除", this.WHSE_Interval)
            }
          }, 500)

        }
      } catch {
        console.log("删除catch", )
      }
      return true;
    },
    onModelClose(iconClick) {
      //iconClick=true为点击左中上角X触发的关闭事件
      //如果返回 false不会关闭弹出框 
      //return false;
      // this.storeRemoveForm()
      this.$store.commit("setTabelText", true)
      this.boxModel = false;
    },
    async modelOpenBefore(row) {
      this.$store.commit("setTabelText", false)
      this.CreateUserBoole = row.CreateID == this.$store.state.userID
      this.rowAuditStatus = await row.AuditStatus
      if (JSON.stringify(row) == "{}") {
        this.rowAuditStatus = 0
        this.CreateUserBoole = true
      }
      if (this.$route.path != "/q_sales_contract" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
        this.boxButtons[0].hidden = true
        this.detailOptions.buttons.forEach(item => {
          if (item.name != "导出" && item.name != "刷新") {
            item.hidden = true
          }
        })
      } else {
        this.boxButtons[0].hidden = false
        this.detailOptions.buttons.forEach(item => item.hidden = false)
      }
    },
    modelOpenAfter(row) {
      this.rowschild = null
      // this.editFormFields.Delivery_status = "0"
      // this.editFormFields.Install_status = "0"

      this.editFormOptions.forEach(item => {
        item.forEach(x => {
          // if (x.field == "Delivery_status" || x.field == "Install_status") {
          //   try {
          //     x.hidden = true
          //   } catch (error) {
          //     console.error(error);
          //   }
          // }
          if (x.field == "Sales_state" || x.field == "Logistics_status") {
            x.hidden = true
          }
          if (this.currentAction == "Add") {
            this.editFormFields.Sales_state = 0
          }

          x.disabled = false
          if (x.field == "Install_service" && this.currentAction != "Add") {
            x.disabled = this.editFormFields.Contract_type == "0"
          }
          if (x.field == "Contract_type") {
            x.onChange = (e) => {
              if (!(e == true)) {
                this.editFormFields.Install_service = "2"
              }
              this.editFormOptions.forEach(i => {
                i.forEach(t => {
                  if (t.field == "Install_service") {
                    t.disabled = !(e == true)
                  }
                })
              })

            }
          }
          if (x.field == "Tax_rate") {
            if (this.currentAction == "Add") {
              x.onChange = (e) => {
                let detailDate = this.$refs.detail.rowData
                detailDate.forEach(d => {
                  if (d.Goods_price) {
                    const num = d.Goods_price / (1 + +e)
                    d.Tax_exclusive_goods_price = this.base.roundToFourDecimals(num)
                    if (d.Goods_num) {
                      // const num = d.Goods_price  / (1 + +e)* d.Goods_num
                      let wsjg = d.Goods_price / (1 + +e)
                      wsjg = this.base.roundToFourDecimals(wsjg)
                      let num = wsjg * d.Goods_num
                      d.Tax_exclusive_total_price = this.base.roundToFourDecimals(num)
                    }
                  }
                })
              }
            } else {
              x.disabled = true
            }
          }
          if (x.field == "Voucher_sub" || x.field == "Signed_num" || x.field == "Signed_price") {
            x.disabled = true
          }
          if (this.$route.path != "/q_sales_contract" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
            x.disabled = true
          }
        })
      })
    },
    async getSummary(formData) {
      let detailRowData = this.$refs.detail.rowData
      let summaryPrc = 0
      let summaryNum = 0
      let num = 0
      await detailRowData.forEach(item => {
        summaryPrc += +item.Total_price
        summaryNum += +item.Goods_num
        if (item.Install_status == null) {
          item.Install_status = "0"
        }

        if (item.Goods_sub && item.Goods_name && item.Goods_num && item.Install_status != null) num++
      })
      // formData.mainData.Signed_num = summaryNum
      // formData.mainData.Signed_price = summaryPrc
      if (detailRowData.length == num) {
        return true
      } else {
        this.base.ElMessageFn("请正确选择商品")
        return false
      }
    },
    testAdd(formData) {
      if (!this.$refs.detail.rowData.length) {
        this.base.ElMessageFn('明细表不可为空', "error")
        return false
      }
      if (!this.editFormFields.WHSE_no) {
        this.base.ElMessageFn('请选择销售机构')
        return false
      }
      if (!this.editFormFields.Contract_type) {
        this.base.ElMessageFn('请选择合同类型')
        return false
      }
      if (!this.editFormFields.Install_service) {
        this.base.ElMessageFn("请选择安装服务")
        return false;
      }
      if (!this.editFormFields.Project_name) {
        this.base.ElMessageFn("请填写项目名称")
        return false;
      }
      formData.mainData.Zhibao_state = this.editFormFields.Zhibao_date > this.base.getDate(true) ? 1 : 0
      let boole2 = formData.detailData.some(item => +item.Goods_num === 0)
      if (boole2) {
        this.base.ElMessageFn("明细表中数量不可为零")
        return false;
      }
      let boole = formData.detailData.some(item => item.Goods_num == "" || item.Goods_num == null || item.Goods_num == undefined)
      if (boole) {
        this.base.ElMessageFn("明细表中请填写数量")
        return false;
      }
      let boole3 = formData.detailData.every(item => +item.Goods_num > 0 && +item.Goods_num)
      if (!boole3) {
        this.base.ElMessageFn("明细表中数量请填写有效正数")
        return false;
      }

      // let boole1 = formData.detailData.some(item => item.Goods_price === "" || item.Goods_price === null || item.Goods_price === undefined)
      // if (boole1) {
      //   this.base.ElMessageFn("明细表中请填写单价")
      //   return false;
      // }
      // let boole22 = formData.detailData.every(item => item.Goods_price!==""||item.Goods_price!==null|| item.Goods_price === undefined||item.Goods_price?(""+item.Goods_price).trim()!=="":+item.Goods_price)
      // if (!boole22) {
      //   this.base.ElMessageFn("明细表中单价不可为空")
      //   return false;
      // }
      // let boole33 = formData.detailData.every(item => +item.Goods_price >= 0 )
      // if (!boole33) {
      //   this.base.ElMessageFn("明细表中单价请填写有效正数")
      //   return false;
      // }

      let booleP3 = formData.detailData.every(item => item.Install_status != "" || item.Install_status != null)
      if (!booleP3) {
        this.base.ElMessageFn("明细表中请选择安装状态")
        return false;
      }
      formData.mainData.Logistics_status = 0
      return true
    },

  },

};
export default extension;